﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2023 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.

using Furion.EventBus;

namespace Abc.Core.EventBus;
/// <summary>
/// 关系数据库：SQL Server、MySql、PgSql等等
/// </summary>
public class RdbEventSourceStorer : IEventSourceStorer
{
    public RdbEventSourceStorer()
    {
    }

    //往数据库中写入一条
    public async ValueTask WriteAsync(IEventSource eventSource, CancellationToken cancellationToken)
    {
        //await _redisClient.WriteAsync(...., cancellationToken);
        //await _sysEventSourceStorerRepository.InsertNowAsync(new SysEventSourceStorer());

        var eventSourceStorer = new SysEventSourceStorer();
        eventSourceStorer.EventId = eventSource.EventId;
        eventSourceStorer.Payload = eventSource.Payload.ToJson();

        await SqlSugarHelper.Db.CopyNew().InsertAsync<SysEventSourceStorer>(eventSourceStorer);

        //await Scoped.CreateAsync(async (_, scope) =>
        //{
        //    var services = scope.ServiceProvider;
        //    var _repository = Db.GetRepository<SysEventSourceStorer>(services);
        //    var result = await _repository.InsertNowAsync(eventSourceStorer);
        //});
    }

    // 从  数据库 中读取一条
    public async ValueTask<IEventSource> ReadAsync(CancellationToken cancellationToken)
    {
        //Console.WriteLine($"EventSource：{DateTime.Now:yyyy-MM-dd HH:mm:ss} ");

        //读取数据，直到有数据才返回
        return await EventBusHelper.Instance.ReadAsync(cancellationToken);
    }
}
